package kz.edu.sdu.itech.qms;

import kz.edu.sdu.itech.qms.util.Logger;


public class Client extends Thread implements Runnable {
   static Logger log = new Logger(Client.class.getName());

   protected String clientName = "";
   protected int clientType;
   protected String clientTicket = "";
   protected QMS qms;

   public long create, queue, serve, servedone;

   public static String genName(){
      int n = QMS.names.length;
      return String.format("%s", QMS.names[QMSProps.R.nextInt(n)]);
   }

   public Client(){
      clientName = genName();
      clientType = QMSProps.R.nextInt(5);
      create = System.currentTimeMillis();
      QMSProps.clients_total++;
   }

   public Client(QMS q) {
      this();
      qms = q;
//      log.debug("created");
   }

   public String getClientName() {
      return clientName;
   }

   public void setClientName(String clientName) {
      this.clientName = clientName;
   }

   public int getClientType() {
      return clientType;
   }

   public void setClientType(int clientType) {
      this.clientType = clientType;
   }

   public String getClientTicket() {
      return clientTicket;
   }

   public void setClientTicket(String clientTicket) {
      this.clientTicket = clientTicket;
   }

   public QMS getQms() {
      return qms;
   }

   public void setQms(QMS qms) {
      this.qms = qms;
   }

   public void setTicketID(int k){
      String s = ""+k;
      while (s.length() < QMSProps.QSL) s = "0"+s;
      setClientTicket(clientType + s);
   }

   @Override
   public void run() {
      log.debug(String.format("%s: try ticket", getClientName()));
      while (!QMSProps.DONE) {
         if (!qms.getQ(clientType).put(this)) {
            log.debug(String.format("%s: queue is full. sleep 1s", getClientName()));
            try {
               Thread.sleep(1000);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         } else {
            log.debug(String.format("%s: took ticket", getClientTicket()));
            QMS.set.remove(this);
            break;
         }

      }
   }

}
